//
//  AppController.m
//  ChipmunkEditor
//
//  Created by Rewolf Us on 11-2-3.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "AppController.h"
#import "TestbedLayer.h"
#import "DrawLayer.h"
#import "cmTypes.h"

@implementation AppController
@synthesize objects;
@synthesize testbedLayerDelegate;
@synthesize drawLayerDelegate;

static AppController *sharedAppController=nil;

-(id)init{
	if (self=[super init]) {
		sharedAppController=self;
		objects=[[NSMutableArray alloc] init];
	}
	return self;
}

+(AppController*)sharedAppcontroller{
	return sharedAppController;
}

#pragma mark Sheets
//circle
-(IBAction)showAddCircleSheet:(id)sender{
	//engine stop?
	[NSApp beginSheet:addCircleSheet
	   modalForWindow:mainWindow
		modalDelegate:nil
	   didEndSelector:NULL 
		  contextInfo:NULL];
}

-(void)addCircleWithX:(float)aX Y:(float)aY radius:(float)radius{
	[circle_x setObjectValue:[NSNumber numberWithFloat:aX]];
	[circle_y setObjectValue:[NSNumber numberWithFloat:aY]];
	[circle_r setObjectValue:[NSNumber numberWithFloat:radius]];
	[NSApp beginSheet:addCircleSheet
	   modalForWindow:mainWindow
		modalDelegate:nil
	   didEndSelector:NULL 
		  contextInfo:NULL];
}

-(IBAction)endAddCircleSheet:(id)sender{
	//addcircle code
	CmCircle *newCircle=[self createCirle:[circle_name stringValue]
										X:[[circle_x objectValue] floatValue]
										Y:[[circle_y objectValue] floatValue]
									 Mass:[[circle_m objectValue] floatValue]
								   Radius:[[circle_r objectValue] floatValue]];
	[self willChangeValueForKey:@"objects"];
	[objects addObject:(CmObject *)newCircle];
	[self didChangeValueForKey:@"objects"];
	[NSApp endSheet:addCircleSheet];
	[addCircleSheet orderOut:sender];
}

#pragma mark add

-(CmCircle *)createCirle:(NSString *)aName X:(float)aX Y:(float)aY Mass:(float)aMass Radius:(float)aRadius{
	CmCircle *newCircle=[[CmCircle alloc] init];
	newCircle.cmName=aName;
	newCircle.radius=aRadius;
	newCircle.mass=aMass;
	newCircle.pos=cpv(aX,aY);
	//draw it out...
	[testbedLayerDelegate addACircle:newCircle];
	return newCircle;
}

#pragma mark Toolbar

-(BOOL)validateToolbarItem:(NSToolbarItem *)theItem{
	if(([theItem tag]==1001 | [theItem tag]==1001) && [testbedLayerDelegate isEngineRunning])
		return NO;//start engine reset engine on/off
	if([theItem tag]==1002 && ![testbedLayerDelegate isEngineRunning])
		return NO;//stop engine on/off
	return YES;
}

//toolbar Actions
-(IBAction)startEngine:(id)sender{
	[testbedLayerDelegate startEngine];
}

-(IBAction)stopEngine:(id)sender{
	[testbedLayerDelegate stopEngine];
}

-(IBAction)resetEngine:(id)sender{
	NSLog(@"%@ pushed",sender);
}

-(IBAction)debugModeToggle:(id)sender{
	
}

#pragma mark draw
-(IBAction)startDrawACircle:(id)sender{
	[drawLayerDelegate enableDrawing];
}

-(void)dealloc{
	[objects release];
	[super dealloc];
}


@end
